// 扫描线

use crate::solution::Solution;

impl Solution {
    pub fn rectangle_area(rectangles: Vec<Vec<i32>>) -> i32 {
        let mut heights = vec![];
        for v in rectangles.iter() {
            heights.push(v[1]);
            heights.push(v[3]);
        }
        heights.sort();

        let mut rs = rectangles;
        rs.sort_by(|a, b| a[0].cmp(&b[0]));

        let mut res = 0;
        let mut height = 0;
        for h in heights.iter() {
            let a = (*h - height) as i64;
            let mut b = 0;
            let mut pre = 0;
            for r in rs.iter() {
                if r[1] <= height && r[3] >= *h {
                    b += (pre.max(r[2]) - pre.max(r[0])) as i64;
                    pre = pre.max(r[2]);
                }
            }
            height = *h;
            res += (a * b) % 1000000007;
        }
        (res % 1000000007) as i32
    }
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_1() {
        let rectangles: Vec<Vec<i32>>  = vec![vec![0,0,2,2],vec![1,0,2,3],vec![1,0,3,1]];
        let result = Solution::rectangle_area(rectangles);
        println!("{}", result);

        assert_eq!(result, 6);
    }

    #[test]
    fn test_2() {
        let rectangles: Vec<Vec<i32>>  = vec![vec![0,0,1000000000,1000000000]];
        let result = Solution::rectangle_area(rectangles);
        println!("{}", result);

        assert_eq!(result, 49);
    }


}
